package com.lance.answer.question_answer.xj_new;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lance.answer.dto.Item;
import com.lance.answer.dto.QuestionDetailNew;
import com.lance.answer.dto.TestExam;
import com.lance.answer.dto.XjCourseVideoInfo;
import com.lance.answer.gui.answer.DealJsonString;
import com.lance.answer.gui.answer.Question;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.HttpUtil;
import com.lance.answer.util.XinJiangUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.Semaphore;

/**
 * 2021-11-1 获取视频的作业
 */
public class BatchGetAnswersByTeacherJson1101 {


    public static List<WebElement> findElementsByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<List<WebElement>>)
                d -> d.findElements(By.cssSelector(cssSelector))));
    }

    public static WebElement findElementByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<WebElement>)
                d -> d.findElement(By.cssSelector(cssSelector))));
    }

    public static void main(String[] args) throws Exception {

        WebDriver driver = Util.getDriver(null);
        String url = "https://xjskk.open.com.cn/teacherspace-auth/#/login";
        // 打开指定的网站
        driver.get(url);
        Thread.sleep(200);

        for (WebElement we : driver.findElements(By.className("el-input__inner"))) {
            if ("text".equals(we.getAttribute("type"))) {
                we.sendKeys(new String[]{"lijunj"});
            }
            if ("password".equals(we.getAttribute("type"))) {
                we.sendKeys(new String[]{"lijunj"});
            }
        }
        driver.findElement(By.cssSelector("button[class='el-button login-ruleForm-btn el-button--primary']")).click();

        // 进入课程观察员角色的页面

        findElementByCssSelector(driver, "div[title='课程观察员']", 20).click();

        Thread.sleep(5000);


        Set<Cookie> cookies = driver.manage().getCookies();
        String studentSpaceProfile = Util.getStudentSpaceProfile(cookies);
        String authorization = Util.getAuthorization(cookies);
        // 初始化头部
        Map<String, String> heads = XinJiangUtil.initHttpHeads(studentSpaceProfile, authorization);

        String cookie = Util.getCookie(cookies);


        Map<Integer,String> cMap = Maps.newHashMap();


        //  E:\XjStudentCourseInfoTmp\names\tmp


        List<String> ids = Lists.newArrayList();
        for(File f1:new File("D:\\新疆一体化视频作业").listFiles()){
            ids.add(f1.getName());
        }


        InputStream inputStream = new FileInputStream("E:\\排名map.txt");
        List<String> allKeyValues = IOUtils.readLines(inputStream, "utf-8");

        Map<String,String> mapTmp = Maps.newHashMap();
        for(String keyValues:allKeyValues){
            String[] strs = keyValues.split("&");
            String k1 = strs[0];
            String v1 = strs[1];
            mapTmp.put(k1,v1);
        }


        for(File file:new File("E:\\XjStudentCourseInfoTmp\\names").listFiles()){
            String fileName = file.getName();
           String code =  fileName.substring(0,fileName.length()-5);
           if(!ids.contains(code)){
               System.err.println("code:"+code);
               System.err.println("mapTmp.get(code):"+mapTmp.get(code));
               cMap.put(Integer.parseInt(code),mapTmp.get(code));
           }
        }

    //    Thread.sleep(200000);


        cMap.clear();
        cMap.put(42276,"人文社会科学基础");

        for(int openCourseId:cMap.keySet()){

           try {
               String subjectName = cMap.get(openCourseId);
               String getUrl1 = "https://xjskk.open.com.cn/api/teacher/teacher-space-service/taskCatalogs?openCourseId="+openCourseId;
               String courseInfoJson = HttpUtil.get(getUrl1, cookie, heads);

               XjCourseVideoInfo videoInfo = JSON.parseObject(courseInfoJson,XjCourseVideoInfo.class);

               System.err.println("videoInfo:"+videoInfo);

               List<String> idList = Lists.newLinkedList();
               List<XjCourseVideoInfo.ContentDTO> contentDTOList = videoInfo.getContent();
               for(XjCourseVideoInfo.ContentDTO contentDTO:contentDTOList){
                   for(XjCourseVideoInfo.ContentDTO.ExaminesDTO examinesDTO:contentDTO.getExamines()){
                       idList.add(examinesDTO.getPaperUid());
                   }
               }


               List<String> papers = Lists.newLinkedList();
               for(String paperId:idList){
                   System.err.println("paperId:"+paperId);
                   //      String getUrl2 = "https://xjskk.open.com.cn/api/teacher/teacher-space-service/testPaper/getPaperById?testPaperId="+paperId;
                   String getUrl2 = "https://xjskk.open.com.cn/api/teacher/teacher-space-service/testPaper/getPaperById?testPaperId="+paperId;
                   String result = HttpUtil.get(getUrl2, cookie, heads);
                   System.err.println("result:"+result);
                   papers.add(result);
               }
               save(papers,openCourseId,subjectName);
               Thread.sleep(5000);
           }catch (Exception e){
           }
        }


        Thread.sleep(1000);
        //   driver.close();
        //  Util.switchToFirst(driver);


        System.err.println("end........");
//        driver.quit();


    }

    public static void save( List<String> papers,int  openCourseId,String subjectName)throws Exception{





        List<Question> questions = Lists.newArrayList();
        for (String json:papers){

            QuestionDetailNew questionDetail = JSONObject.parseObject(json, QuestionDetailNew.class);

            QuestionDetailNew.ContentDTO contentDTO= questionDetail.getContent();
            if(contentDTO == null){
                continue;
            }

            if(null == contentDTO.getItems()){
                System.err.println("??????:"+questionDetail);
                continue;
            }
            for (QuestionDetailNew.ContentDTO.ItemsDTO itemsDTO:contentDTO.getItems()) {
                Question question = new Question();
                question.setTitle(itemsDTO.getI2());
                question.setScore(itemsDTO.getI9());
                int i3 = itemsDTO.getI3()==null?888:itemsDTO.getI3();
                question.setQuestionType(i3);


                if (i3 <= 3) {
                    if (i3 == 1) {
                        question.setQuestionTypeDesc("单选题");
                    } else if (i3 == 2) {
                        question.setQuestionTypeDesc("多选题");
                    } else {
                        question.setQuestionTypeDesc("判断题");
                    }


                    List<Item> items = Lists.newArrayList();
                    question.setItems(items);
                    List<String> answers = itemsDTO.getI6();
                    for (String answer : answers) {
                        Item item = new Item(answer, "");
                        items.add(item);
                    }

                    // 正确的答案所在的位置
                    List<String> correctIndex = itemsDTO.getI7();
                    List<String> correctList = Lists.newArrayList();
                    for (String cIndex : correctIndex) {
                        int index = Integer.parseInt(cIndex);
                        if (i3 != 3) {
                            correctList.add(answers.get(index));
                        } else {

                            System.err.println("???????????????:"+JSON.toJSONString(answers)+"\t correctIndex"+JSON.toJSONString(correctIndex));

                            if (correctIndex.get(0).equals("0")) {
                                correctList.add("对");
                            }else if (correctIndex.get(0).equals("1")) {
                                correctList.add("错");
                            }
                        }
                    }
                    String[] correctArray = new String[]{};
                    correctArray = correctList.toArray(correctArray);
                    System.err.println("correctArray:" + JSON.toJSONString(correctArray));
                    question.setCorrectArray(correctArray);

                    System.err.println("????????????111:" + JSON.toJSONString(question.getCorrectArray()));
                } else {
                    if (i3 == 4) {
                        question.setQuestionTypeDesc("填空题");
                    } else {
                        question.setQuestionTypeDesc("简答题");
                    }
                    // 正确的答案所在的位置
                    List<String> answers = itemsDTO.getI6();
                    String[] correctArray = new String[]{};
                    correctArray = answers.toArray(correctArray);
                    question.setCorrectArray(correctArray);
                }

                questions.add(question);

                System.err.println("??????????????222:" + JSON.toJSONString(question.getCorrectArray()));
            }
        }


        //   Collections.sort(questions);
        List<Map<String, Object>> answers = new ArrayList<>();
        for (Question question : questions) {
            String title = question.getTitle();
            title = Util.dealContent(title);
            Map<String, Object> answerMap = new HashMap<>();
            answerMap.put("questionType", question.getQuestionType());
            answerMap.put("answerType", "click");
            answerMap.put("questionTypeDesc", question.getQuestionTypeDesc());
            answerMap.put("questionTitle", DealJsonString.delHTMLTag(title));
            answerMap.put("questionCode", question.getQuestionCode());
            answerMap.put("items", question.getItems());
            answerMap.put("answers", question.getCorrectArray());
            System.err.println("question.getCorrectArray():" + JSON.toJSONString(question.getCorrectArray()));
            answerMap.put("score", question.getScore());
            answers.add(answerMap);
        }

        FileUtils.write(new File("D:\\新疆一体化视频作业\\" + openCourseId + "\\" + subjectName + "（视频作业）.json"), JSONObject.toJSONString(answers, SerializerFeature.PrettyFormat), "utf-8");

        Thread.sleep(1000);
    }


}
